//
//  ShellHomeViewModel.m
//  ShellWallert
//
//  Created by lvzhao on 2019/10/3.
//  Copyright © 2019 VV. All rights reserved.
//

#import "ShellHomeViewModel.h"
#import "ShellMilestoneModel.h"
#import "ShellCountryDataModel.h"
#import "SocketRocketUtility.h"
#import "ShellTotalRewardModel.h"

@implementation ShellHomeViewModel

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self createotificationCenter];
    }
    return self;
}


//监听通知
- (void)createotificationCenter{
    
    
    @weakify(self);
        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kWebSocketdidReceiveMessageNote object:nil] subscribeNext:^(NSNotification * _Nullable x) {
            @strongify(self);
            NSDictionary *resultDictionary = x.object;
            if([resultDictionary[@"type"] isEqualToString:@"hashAward"]){
                ShellTotalRewardModel *rewardModel = [ShellTotalRewardModel mj_objectWithKeyValues:resultDictionary[@"data"]];
                [self.reloadSubject sendNext:rewardModel];
            } else {
                
                ShellUserDetailModel *detailModel = [LZToolCache getUserInfo];
                NSDictionary *dataDictionary = resultDictionary[@"data"];
                if([dataDictionary[@"userEmail"] isEqualToString:detailModel.email]){
                    
                    
                    NSString *orderAmount = [NSString stringWithFormat:@"%@",dataDictionary[@"orderAmount"]].saveDecimal;
                    NSDictionary *params = @{@"orderAmount":orderAmount?:@"",
                                             @"type":dataDictionary[@"type"]?:@"",
                                             @"standardCurrency":dataDictionary[@"standardCurrency"]?:@"",
                                             @"awardUsdt":dataDictionary[@"awardUsdt"]?:@""};
                    
                    [LZToolView showAlertType:LZAlertViewTypeGrabOrder withTitle:LZLocalizedString(@"您有新的订单") message:@"" cancel:@"" sure:@"" objectDict:params cancelBlock:^(id  _Nullable object) {} sureBlock:^(id  _Nullable object) {
                        //发送请求 抢单 然后 请求成功
                        @strongify(self);
                        [self startGrabOrder:dataDictionary];
                                        
                    }];
                }
            }
        }];
        
    
    
        
        //断开连接的通知
        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kWebSocketDidCloseNote object:nil] subscribeNext:^(NSNotification * _Nullable x) {
            
            NSString *url = [NSString stringWithFormat:@"%@/%@",kWebSocketUrl,k_userToken];
            [[SocketRocketUtility instance] SRWebSocketOpenWithURLString:url];
        }];

    
      //退到后台
       [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillResignActiveNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
           
           [[SocketRocketUtility instance] SRWebSocketClose];
       }];

       
        //从后台进入
       [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidBecomeActiveNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
           @strongify(self);
           [self getHashAward];
       }];
}

/**
 Convert 创建长链接
 */
- (void)createWebSocket{
    NSString *url = [NSString stringWithFormat:@"%@/%@",kWebSocketUrl,k_userToken];
    [[SocketRocketUtility instance] SRWebSocketOpenWithURLString:url];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


/**
Convert 处理抢单
*/
- (void)startGrabOrder:(NSDictionary *)dataDictionary{
    
    NSDictionary *params = @{@"orderCode":dataDictionary[@"code"]};
    
    
    [LZNetworkingManager lz_request:@"post" url:kReadScramble params:params success:^(id  _Nullable responseObject) {
        
        if([responseObject[kResultStatus] isEqualToString:kCode]){
            [LZToolView dismiss];
            showDelayedDismissTitle(LZLocalizedString(@"抢单成功"), nil);
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:k_APPUserGrabOrderSuccessNotificationName object:nil];
            });
        }
    } failure:^(NSError * _Nullable error) {
        
    } isLoading:YES isFailTip:YES];
    

    
}


/**
 Convert 请求首页的静态数据
 */
- (void)getStaticInfo:(BOOL)isLoading{
      @weakify(self);
      [LZNetworkingManager lz_request:@"get" url:kGetStaticInfo params:nil success:^(id  _Nullable responseObject) {
          if([responseObject[kResultStatus] isEqualToString:kCode]){
              @strongify(self);
              [self.countryArray removeAllObjects];
              [self.milestoneArray removeAllObjects];
              NSDictionary *dataDictionary = responseObject[kResultData];
              self.hashRateDesc = dataDictionary[@"hashRateDesc"];      //算力
              self.creditScoreDesc = dataDictionary[@"creditScoreDesc"]; //信用分
              NSArray *milepostArray = dataDictionary[@"allMilepost"];
              for (int i = 0; i < milepostArray.count; i++) {
                  ShellMilestoneModel *milestoneModel = [ShellMilestoneModel mj_objectWithKeyValues:milepostArray[i]];
                  [self.milestoneArray addObject:milestoneModel];
              }
              
              //全网算力
              NSDictionary *networkHashRate = dataDictionary[@"networkHashRate"];
              self.hashRateModel = [ShellNtworkHashRateModel mj_objectWithKeyValues:networkHashRate];
              
              //国家节点
              NSArray *countryDataArray = dataDictionary[@"countryData"];
              for (int i = 0; i < countryDataArray.count; i++) {
                   ShellCountryDataModel *countryDataModel = [ShellCountryDataModel mj_objectWithKeyValues:countryDataArray[i]];
                  [self.countryArray addObject:countryDataModel];
              }
              [self.reloadSubject sendNext:@(1)];
          }
      } failure:^(NSError * _Nullable error) {} notwork:^(NSError * _Nullable error) {} isLoading:isLoading isFailTip:YES];
       
    
}
/**
 Convert 请求矿池奖励
 */
- (void)getHashAward{
    
    if(k_userToken.length == 0)return;
    [self.dataArray removeAllObjects];
    @weakify(self);
    NSString *url = [NSString stringWithFormat:@"%@/1",kHashAwardList];
    [LZNetworkingManager lz_request:@"get" url:url params:nil success:^(id  _Nullable responseObject) {
         if([responseObject[kResultStatus] isEqualToString:kCode]){
             @strongify(self);
             [self.dataArray removeAllObjects];
             NSArray *dataArray = responseObject[kResultData];
             for (int i = 0; i < dataArray.count; i++) {
                ShellTotalRewardModel *rewardModel = [ShellTotalRewardModel mj_objectWithKeyValues:dataArray[i]];
                 [self.dataArray addObject:rewardModel];
             }
             [self.reloadSubject sendNext:@(1)];
             
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 //建立长链接
                 @strongify(self);
                 [self createWebSocket];
             });
             
         }
     } failure:^(NSError * _Nullable error) {} notwork:^(NSError * _Nullable error) {} isLoading:NO isFailTip:NO];
    
    
}

/**
 Convert 请求我的账户信用, 算力
 */
- (void)getReadAccount{
    
    if(k_userToken.length == 0)return;
    @weakify(self);
    [LZNetworkingManager lz_request:@"get" url:kReadAccount params:nil success:^(id  _Nullable responseObject) {
        if([responseObject[kResultStatus] isEqualToString:kCode]){
            @strongify(self);
            NSDictionary *dataDictionary = responseObject[kResultData];
            
            self.accountModel = [ShellReadAccountModel mj_objectWithKeyValues:dataDictionary];
            [self.reloadSubject sendNext:@(1)];
        }
    } failure:^(NSError * _Nullable error) {} notwork:^(NSError * _Nullable error) {} isLoading:YES isFailTip:YES];
}


- (NSMutableArray *)milestoneArray{
    
    if(!_milestoneArray){
        _milestoneArray = [[NSMutableArray alloc] init];
    }
    return _milestoneArray;
    
}

- (NSMutableArray *)countryArray{
    
    if(!_countryArray){
        _countryArray = [[NSMutableArray alloc] init];
    }
    return _countryArray;
    
}

@end
